<html>
<head>
	<title>nTube v1.5-legacy</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<style type="text/css" id="__ntheming_global">
	html {
		background-color: black;
		color: white;
	}
	</style>
	<style type="text/css" id="__ntheming_global_font">
	html {
		font-family: sans-serif;
	}
	</style>
	<style>
	html {
		font-size: small;	
	}
	input {
		font-family: inherit;
		background-color: inherit;
		color: inherit;	
	}
	h1 {
		font-family: inherit;
		font-size: small;
	}
	.changelog_entry {
		line-height: 80%;	
	}
	a {
		color: inherit;
		text-decoration: none;	
	}
.rainbow {
   /* Chrome, Safari, Opera */
  -webkit-animation: rainbow 3s infinite; 
  
  /* Internet Explorer */
  -ms-animation: rainbow 3s infinite;
  
  /* Standar Syntax */
  animation: rainbow 3s infinite; 
}

/* Chrome, Safari, Opera */
@-webkit-keyframes rainbow{
  0%{color: orange;}	
  10%{color: purple;}	
	20%{color: red;}
	40%{color: yellow;}
	60%{color: green;}
	100%{color: blue;}
	100%{color: orange;}	
}
/* Internet Explorer */
@-ms-keyframes rainbow{
  0%{color: orange;}	
  10%{color: purple;}	
	20%{color: red;}
	40%{color: yellow;}
	60%{color: green;}
	100%{color: blue;}
	100%{color: orange;}	
}

/* Standar Syntax */
@keyframes rainbow{
  0%{color: orange;}	
  10%{color: purple;}	
	20%{color: red;}
	40%{color: yellow;}
	60%{color: green;}
	100%{color: blue;}
	100%{color: orange;}
}
	</style>
	<script type="text/javascript" >
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}	

function canStoreData() {
	return typeof Storage == "function" || navigator.cookieEnabled;
}

function readSettings() {
	if (!canStoreData()) {
		return null;	
	}
	if (localStorage.getItem("_ntube_settings") != null) {
		return localStorage.getItem("_ntube_settings");
	}else {
		return getCookie("settings");
	}	
}

function readSettingsToJSON() {
	var rs = readSettings();
	if (rs == null) {
		return null;	
	}
	return JSON.parse(b64DecodeUnicode(rs));
}

function applyTheme(themeCode) {
	console.log("[nTube: nTheming] Loading CSS for this page...");
	send_request("/api/get_css?eurl=" + themeCode, "", function () {
		console.error("[nTube: nTheming] Failed to load CSS!");
	}, function (data) {
		document.getElementById("__ntheming_global").innerHTML = data;
	});
}

function applyFont(fontCode) {
	console.log("[nTube: nTheming] Loading font for this page...");
	send_request("/api/get_font?eurl=" + fontCode, "", function () {
		console.error("[nTube: nTheming] Failed to load font!");
	}, function (data) {
		document.getElementById("__ntheming_global_font").innerHTML = data;
	});
}

function b64DecodeUnicode(str) {
    try {
 		return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        	return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    	}).join(''));   	
    }catch (ex) {
    	return atob(str);	
    }
}
	
function seconds2time (seconds) {
	if (seconds == undefined) {
		return seconds;	
	}
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    var seconds = seconds - (hours * 3600) - (minutes * 60);
    var time = "";

    if (hours != 0) {
      time = hours+":";
    }
    if (minutes != 0 || time !== "") {
      minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
      time += minutes+":";
    }
    if (time === "") {
      time = seconds+"s";
    }
    else {
      time += (seconds < 10) ? "0"+seconds : String(seconds);
    }
    return time;
}	
	
	function load(query0) {
		if (query0 == null || query0.length == 0) {
			alert("I'm not going to search for nothing.\n(Query was NULL or it's length was equal to 0)");
			return;
		}
		var searchR = document.getElementById("searchResults") ;
		while (searchR.firstChild) {
   			searchR.removeChild(searchR.firstChild);
		}
		var channelData = "";
		var searchFor0 = document.createElement("h2");
		searchFor0.innerHTML = "Search";
		searchFor0.style.textAlign = "center";
		searchR.appendChild(searchFor0);
		var searchFor = document.createElement("p");
		searchFor.innerHTML = "Searching for " + query0 + "...";
		searchFor.style.textAlign = "center";
		searchFor.style.lineHeight = "20%";
		searchFor.style.fontSize = "x-small";
		searchR.appendChild(searchFor);
		send_request("/search_video_api?query=" + encodeURIComponent(query0) , "", function() {
			channelData = "error";
		}, function(data) {
			channelData = data;
			//var x = data.split("\n");
			var query = b64DecodeUnicode(data);
			//document.getElementById("vivon").innerHTML = atob(x[3]);
			try {
				var qJ = JSON.parse(query);
				var videos = qJ.videos;
				var i = 0;
				searchFor.innerHTML = "Results for " + query0 + ".";
				for (; i < videos.length; i++) {
					var video = videos[i];
					var vidTitle = video.title;	
					var vidURL = video.url.replaceAll("https://www.youtube.com/", "/").replaceAll("http://www.youtube.com/", "/");
					var txt = document.createElement("a");
					var searchResult = document.createElement("div");
					searchResult.style.width = "248px";
					searchResult.style.height = "158px";
					searchResult.style.border = "1px solid green";
					searchResult.style.display = "inline-table";
					if (video.type) {
						if (video.type === "playlist") {
							txt.innerHTML = vidTitle + " [PLAYLIST]";
						}else if (video.type === "channel") {
							txt.innerHTML = vidTitle + " [CHANNEL]";
						}else {
							txt.innerHTML = vidTitle + " [" + seconds2time(video.duration) + "]";
						}
					}
					txt.href = vidURL;
					txt.style.textDecoration = "none";
					txt.style.color = "inherit";
					searchResult.appendChild(txt);
					searchResult.appendChild(document.createElement("br"));
					try {
						var img0 = document.createElement("a");
						img0.href = vidURL;
						//"http://i.ytimg.com/vi/"
						//+ "/mqdefault.jpg"
						img0.innerHTML = "<img src=\"" + video.vid + "\" alt=\"\">";
						searchResult.appendChild(img0);
					}catch (ex) {
					}
					searchR.appendChild(searchResult);
				}
			}catch (ex) {
				console.error(ex);
			}
		});
		if (channelData == "error") {
			console.error("Failed to query search!");
			return;
		}
	}
	
	function initTrending() {
		var settings = readSettingsToJSON();	
		if (settings != null && settings.theme) {
			applyTheme(settings.theme);	
		}
		if (settings != null && settings.font) {
			applyFont(settings.font);		
		}
		var stop = false;
		if (typeof fetch == "undefined") {
			stop = true;
			document.getElementById("__no_fetch_warn").style.display = "";
			document.getElementById("__no_fetch_warn").style.visibility = "";
			document.getElementById("__no_fetch_warn").style.color = "orange";
		}
		if (stop) {
			return;			
		}
		document.getElementById("__search").value = "";
		String.prototype.replaceAll = function(searchStr, replaceStr) {
				var str = this;

    			// no match exists in string?
    			if(str.indexOf(searchStr) === -1) {
        			// return string
        			return str;
    			}

    			// replace and remove first match, and do another recursirve search/replace
    			return (str.replace(searchStr, replaceStr)).replaceAll(searchStr, replaceStr);
			}
		send_request("get_trending", "", function () {
			var d = document.getElementById("tr_m");
			d.style.color = "red";
			d.style.fontSize = "large";
			d.innerHTML = "Failed to load trending tab.";
		}, function (data) {
				try {
					//var x = data.split("\n");
					var jsonObject = JSON.parse(b64DecodeUnicode(data));
					var trending = jsonObject.data;
					var d0 = document.getElementById("tr_m");
					var div0 = document.getElementById("trending");
					d0.innerHTML = "Listing " + trending.length + " videos...";
					var i = 0;
					for (; i < trending.length; i++){
						var entry = trending[i];
						var vidT = document.createElement("p");
						//console.log(entry.vidLength);
						vidT.innerHTML = entry.title + " | " + seconds2time(entry.vidLength);
						var vidThumb = document.createElement("a");
						vidThumb.href = "/watch?v=" + entry.id;
						vidThumb.innerHTML = "<img src=\"" + entry.imgURL + "\" alt=\"\">";
						div0.appendChild(vidT);
						div0.appendChild(vidThumb);
					}
					var btrending = jsonObject.bcvideos;
					i = 0;
					var listed = 0;
					var div1 = document.getElementById("trending_bc");
					for (; i < btrending.length; i++){
						var entry = btrending[i];
						var vidT = document.createElement("p");
						//console.log(entry.vidLength);
						vidT.innerHTML = entry.title; //+ " | " + seconds2time(entry.vidLength);
						var vidThumb = document.createElement("a");
						vidThumb.href = entry.url;
						vidThumb.innerHTML = "<img width=\"160px\" height=\"90px\" src=\"" + (entry.thumb) + "\" alt=\"\">";
						if (entry.url.length >= 21) {
							div1.appendChild(vidT);
							div1.appendChild(vidThumb);
							listed += 1;						
						}
					}
					document.getElementById("tr_m_bc").innerHTML = "Listing " + listed + " videos...";
				}catch (ex) {
					console.error(ex);
					var d = document.getElementById("tr_m");
					d.style.color = "red";
					d.style.fontSize = "large";
					d.innerHTML = "Failed to load trending tab.";
				}
		});
	}
	
function send_request(url, data, onFail, onSuccess) {
	if (typeof fetch != "undefined") {
		fetch(url).then(function(response) {
    		return response.text();
   	}).then(function(json) {
   		onSuccess(json);
   	}).catch(function(ex) {
   		console.error(ex);
    		onFail();
  		});	
	}else {
		console.warn("send_request() -> Outdated browser found, attempting fallback method...");
		var http = null;
		if (window.XMLHttpRequest) {
			http = new XMLHttpRequest();		
		}else {
			http = new ActiveXObject("Microsoft.XMLHTTP");
		}
		http.open('POST', url, true);
	   http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	   
	   var hasResponse = false;
	   //var res = "";
	   http.onreadystatechange = function() {
		if (http.readyState == 4 && http.status == 200) {
		//		res = http.responseText;
				onSuccess(http.responseText.split("\n")[4]);
			}
		}
		http.ontimeout = function() {
			alert("nTube: onTimeout() was called when fetching your video!");
		}
		http.send(params);
	}
	//var http = new XMLHttpRequest();
	//var params = data;
	//http.timeout = 0;
	//http.responseType = 'blob';
	//http.open('POST', url, true);
	//http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			
	//var hasResponse = false;
	//var res = "";
	//http.onreadystatechange = function() {
	//	if (http.readyState == 4 && http.status == 200) {
	//		res = http.responseText;
	//		onSuccess(http.responseText);
	//	}
	//}
	//http.ontimeout = function() {
	//	alert("nTube: onTimeout() was called when fetching your video!");
	//}
	//http.send(params);
	
	/*		
	var stop = false;
	var time = 0;
	while (!hasResponse) {
		if (stop) {
			break;
		}
		if (time > 1500) {
			//alert("Timeout occured, try again.");
			onFail();
			stop = true;
		}
		var ix = -1;
		time += 1;
	}*/
}
	
	function clearR() {
		var searchR = document.getElementById("searchResults") ;
		while (searchR.firstChild) {
   		searchR.removeChild(searchR.firstChild);
		}
	}
	</script>
	<div style="width: 100%;border-bottom: 1px solid green;">
	<h1 style="display: inline-block;"><span style="color: red;">n</span><span style="color: lightgreen;">Tube</span></h1>
	<p style="float: right;">version 1.5-legacy</p>
	<h1 id="__no_fetch_warn" style="visibility: hidden;display: none;">fetch() is missing, nTube may not function on your browser.</h1>
	</div>
	<div style="border-bottom: 1px solid orange; width: 100%;line-height: 80%;">
		<p>This page is being reworked, expect some changes to the page UI.</p>
	</div>
</head>
<body onload="initTrending();">
	<center>
	<!-- deprecated <div style="width: 100%;border-bottom: 1px solid green;">
		<a href="mediacenter.html" style="line-height: 40%;">nTV</a>
	</div>-->
	<div id="__ntube__new__primary_div" style="width: 100%;border: 1px solid green;">
		<div style="display: inline-block;padding-left: 5px;padding-right: 5px;">
			<!--<a href="">-->
			<img src="/resources/equaliser.png" alt="NTUBE.nMusic" style="opacity: 0.5;">
			<p style="color: gray;">nMusic<sub style="font-size: x-small;font-family: monospace;">beta</sub></p>
			<!--</a>-->
		</div>
		<div style="display: inline-block;padding-left: 5px;padding-right: 5px;">
			<a href="/mediacenter.html" >
			<img src="/resources/tv.png" alt="NTUBE.nTV" style="opacity: 1;">
			<p  style="">nTV<sub style="font-size: x-small;font-family: monospace;">beta</sub></p> <!--color: gray;-->
			</a>
		</div>
		<div style="display: inline-block;padding-left: 5px;padding-right: 5px;">
			<a href="/changelog">
			<img src="/resources/changelog.png" alt="NTUBE.changelogIcon">
			<p>Changelog</p>
			</a>
		</div>
		<div style="display: inline-block;padding-left: 5px;padding-right: 5px;">
			<a href="/about">
			<img src="/resources/information.png" alt="NTUBE.about">
			<p>About nTube</p>
			</a>
		</div>
		<div style="display: inline-block;padding-left: 5px;padding-right: 5px;">
			<a href="/browser_check" >
			<img src="/resources/browser_check.png" alt="NTUBE.sysCompatCheck">
			<p>Check My Browser</p>
			</a>
		</div>
		<div style="display: inline-block;padding-left: 5px;padding-right: 5px;">
			<a href="/settings">
			<img src="/resources/settings.png" alt="NTUBE.configuration">
			<p>Settings</p>
			</a>
		</div>
	</div>
	<div style="width: 100%;border: 1px solid green;">
	<!--<p style="display:inline;">Enter your search query:</p>-->
	<input id="__search" style="border: 1px solid gray;width: 60%;" placeholder="Search nTube (press ENTER to search)"></input>
	<input type="button" value="Search It!" onclick="load(document.getElementById('__search').value)" /></input>
	<input type="button" value="Clear Results" onclick="clearR();" /></input>
	<script type="text/javascript" >
	// Injects into input form to allow 'ENTER' to search feature.
	document.getElementById("__search").addEventListener("keypress", function (event) {
		if (event.keyCode == 13) {
            event.preventDefault();
            load(document.getElementById('__search').value);
        }
	});
	</script>
	</div>
	</center>
	<div id="searchResults" style="width: 100%;border: 1px solid green;"></div>
	<div>
	<h1 style="font-size: large;">Your subscriptions</h1>	
		<div style="width: 100%;border: 1px solid green;" id="_sub">
			<p style="text-align: center;font-size: small;color: gray;">Just like the features of this software, empty.</p>
		</div>
		<script>
			function sleep(milliseconds) {
  				if (milliseconds <= 0) {
					return;  
  				}
  				var start = new Date().getTime();
  				for (var i = 0; i < 1e7; i++) {
    				if ((new Date().getTime() - start) > milliseconds){
      					break;
    				}
				}
			}
			var settings = readSettingsToJSON();
			if (settings.subscriptions && settings.subscriptions.length > 0) {
				var sub = document.getElementById("_sub");
				var list = settings.subscriptions.reverse();
				sub.innerHTML = "";
				var tasks = [];
				for (var i = 0; i < list.length; i++) {
					(async () => {
						var subscription = list[i];
						var mainDiv = document.createElement("div");
						mainDiv.style.border = "1px solid gray";
						mainDiv.style.width = "auto";
						mainDiv.style.margin = "3px";
						var channelInfo = document.createElement("div");
						var channelIcon = document.createElement("img");
						channelIcon.src = subscription.image;
						channelIcon.style.width = "64px";
						channelIcon.style.height = "64px";
						channelIcon.style.verticalAlign = "middle";
						channelIcon.style.display = "inline";
						channelInfo.appendChild(channelIcon);
						var channelName = document.createElement("a");
						channelName.innerHTML = subscription.cName;
						channelName.style.verticalAlign = "middle";
						channelName.style.display = "inline";
						channelName.style.marginLeft = "5px";
						channelName.style.textDecoration = "none";
						channelName.style.color = "inherit";
						channelName.style.fontWeight = "bold";
						channelName.href = "/channel?c=" + subscription.cid;
						channelInfo.appendChild(channelName);
						var videosDiv = document.createElement("div");
						videosDiv.style.marginLeft = "72px";
						var videosL = document.createElement("p");
						videosL.innerHTML = "Latest Videos";
						videosL.style.borderBottom = "1px solid gray";
						videosDiv.appendChild(videosL);
						var videosI = document.createElement("p");
						videosDiv.appendChild(videosI);
						var videosList = document.createElement("div");
						videosList.style.overflowY = "hidden";
						videosList.style.overflowX = "scroll";
						videosList.style.display = "inline-flex";
						videosList.style.width = "100%";

						var ran = false;
						var ft = await fetch("/channel_api?c=" + subscription.cid);
						var response = await ft.json();
					/*send_request(, "", function() {
						}, function(data) {
							var json = JSON.parse(data);
							console.log(json);
							response = json;
						}
					);*/

						if (response.videos[0].vid == subscription.lastVid) {
							videosI.innerHTML = "There are no new videos! Listing the last few ones...";
							for (var v = 0; v < (response.videos.length > 15 ? 15 : response.videos.length); v++) {
								var vid = response.videos[v];
								var lk = document.createElement("a");
								lk.style.textDecoration = "none";
								lk.style.color = "inherit";
								lk.href = vid.url;
								var vd = document.createElement("div");
								vd.style.border = "1px solid lightgray";
								vd.style.display = "inline-flex";
								var img = document.createElement("img");
								img.src = vid.thumb;
								img.style.width = "300px";
								img.style.height = "160px";
								lk.appendChild(img);
								var t = document.createElement("p");
								t.innerHTML = vid.title + " | " + seconds2time(vid.duration);
								t.style.textAlign = "center";
								lk.appendChild(t);
								vd.appendChild(lk);
								videosList.appendChild(vd);
							}
						}else {
							for (var v = 0; v < response.videos.length; v++) {
								var vid = response.videos[v];
								if (vid.vid == subscription.lastVid) {
									break;
								}
								var lk = document.createElement("a");
								lk.style.textDecoration = "none";
								lk.style.color = "inherit";
								lk.href = vid.url;
								var vd = document.createElement("div");
								vd.style.border = "1px solid lightgray";
								vd.style.display = "inline-flex";
								var img = document.createElement("img");
								img.src = vid.thumb;
								img.style.width = "300px";
								img.style.height = "160px";
								lk.appendChild(img);
								var t = document.createElement("p");
								t.innerHTML = vid.title + " | " + seconds2time(vid.duration);
								t.style.textAlign = "center";
								lk.appendChild(t);
								vd.appendChild(lk);
								videosList.appendChild(vd);
							}
						}

						videosDiv.appendChild(videosList);
						mainDiv.appendChild(channelInfo);
						mainDiv.appendChild(videosDiv);
						sub.appendChild(mainDiv);
					})();
					sleep(220);
				}
			};
		</script>
	</div>
	<div>
	<h1 style="font-size: large;">What's trending?</h1>
		<div>
			<div style="display: inline-table;border: 1px solid green;width: 50%;">
				<h1 style="text-align: center;">Trending Videos on YouTube</h1>
				<p id="tr_m" style="line-height: 10%;color: gray;text-align: center;">Listing -1 videos...</p>
				<div id="trending"></div>			
			</div>		
			<div style="display: inline-table;border: 1px solid green;width: 49%;">
				<h1 style="text-align: center;">Trending Videos on BitChute</h1>
				<p id="tr_m_bc" style="line-height: 10%;color: gray;text-align: center;">Listing -1 videos...</p>
				<div id="trending_bc"></div>
			</div>		
		</div>
	</div>
	<!--<h1 style="font-size: large;">Changelog</h1>-->
	<center>
		<p style="display: inline-block;">nTube from nullUtil 2.6</p>	
	</center>
</body>
</html>
